import { saveTeacher, getMajorTree } from '../../api/user'
import { listByKind, areaList, findColumnList } from '../../api/base'

Page({

  /**
   * 页面的初始数据
   */
  data: {
    pageHeight: 0,
    isDisabled: false,

    subjectList: [],
    showSubject: false,
    selSubjects: [],

    phaseList: [],
    showPhase: false,
    selPhases: '',

    goodAtList: [],
    showGoodAt: false,
    selGoodAt: [],

    focusList: [],
    showFocus: false,
    selFocus: [],

    trainList: [],
    showTrain: false,
    selTrain: [],

    showSchoolType: false,
    schoolTypes: [
      { name: '公办', value: 'STATE'  },
      { name: '民办', value: 'VOLUNTARY'  }
    ],
    schoolType: '',

    form: {
      areaCode: '',
      focus: [],
      goodAtId: [],
      phaseId: 0,
      schoolName: '',
      schoolType: '',
      subjectId: [],
      trainSpecialityId: []
    },

    region: [],
    /** 省市区参数 **/
    province_list:null,
    province_name:null,
    city_list:null,
    city_name:null,
    area_list:null,
    area_name:null,
    addressCity:null,
    multiArray: [],  // 三维数组数据
    multiIndex: [0, 0, 0], // 默认的下标,
    selectProvinceId:null,
    selectCityId:null,
    selectAreaId:null
    /** 省市区参数 **/
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setPageHeight()
    this.getProvince()
    this.init()
  },

  back() {
    wx.navigateBack({ delta: 1 })
  },

  setPageHeight() {
    let windowHeight
    wx.getSystemInfo({
      success: function(res) {
        windowHeight = res.windowHeight
      }
    });
    let query = wx.createSelectorQuery().in(this);
    query.select('.info-nav-wrap').boundingClientRect();
    query.exec((res) => {
      this.setData({
        pageHeight: windowHeight - res[0].height
      })
    });
  },

  init() {
    // 学段
    listByKind('stage').then(res => {
      this.setData({
        phaseList: res
      })
    })

    // 科目
    listByKind('subject').then(res => {
      if (res.length) {
        res.forEach(r => {
          r.isCheck = false
        })
      }
      this.setData({
        subjectList: res
      })
    })
  },

  /** 省市区 start **/
  //获取省份列表
  getProvince(){
    let that = this
    areaList({}).then(res => {
      let provinceList = [...res]  //放到一个数组里面
      let provinceArr = res.map((item)=>{return item.name})  //获取名称
      that.setData({
        multiArray: [provinceArr,[],[]], //更新三维数组  更新完为[['广东','北京'],[],[]]
        province_list: provinceList,  //省级原始数据
        province_name: provinceArr,  //省级全部名称
      })
      let defaultCode = that.data.province_list[0].code //使用第一项当作参数获取市级数据
      if(defaultCode){
        that.setData({
          currentProvinceId: defaultCode  //保存当前省份id
        })
        that.getCity(defaultCode) //获取市区数据
      }
    })
  },

  //根据省份id获取城市
  getCity(code){
    let that = this
    that.setData({
      currentProvinceId: code
    })

    areaList({ parentCode: code }).then(res => {
      let cityArr = res.map((item)=>{return item.name}) //返回城市名称
      let cityList = [...res]
      that.setData({
        multiArray:[that.data.province_name,cityArr,[]],  //更新后[['广东','北京'],['潮州'，'汕头','揭阳'],[]]
        city_list:cityList, //保持市级数据
        city_name:cityArr   //市级名称
      })
      let defaultCode = that.data.city_list[0].code //获取第一个市的区级数据
      if(defaultCode){
        that.setData({
          currentCityId:defaultCode //保存当下市id
        })
        that.getArea(defaultCode) //获取区域数据
      }
    })
  },

  //获取区域
  getArea:function(code){
    let that = this
    that.setData({
      currentCityId:code    //保存当前选择市
    })
    areaList({ parentCode: code }).then(res => {
      let areaList = [...res]
      let areaArr = res.map((item)=>{return item.name}) //区域名
      that.setData({
        multiArray:[that.data.province_name,that.data.city_name,areaArr],
        area_list:areaList, //区列表
        area_name:areaArr   //区名字
      })
    })
  },

  //picker确认选择地区
  bindRegionChange:function(e){
    // 因为在获取省中 北京只有一个选项，导致获取不了北京》北京》第一个
    if(e.detail.value[1]==null || e.detail.value[2]==null){ //如果只滚动了第一列则选取第一列的第一数据
      this.setData({
        multiIndex: e.detail.value,  //更新下标
        addressCity: [this.data.province_list[e.detail.value[0]].name, this.data.city_list[0].name, this.data.area_list[0].name],
        selectProvinceId: this.data.province_list[e.detail.value[0]].code,
        selectCityId: this.data.city_list[0].code,
        selectAreaId: this.data.area_list[0].code,
        'form.areaCode': this.data.area_list[0].code
      })
    }else{
      this.setData({
        multiIndex: e.detail.value,  //更新下标
        addressCity: [this.data.province_list[e.detail.value[0]].name, this.data.city_list[e.detail.value[1]].name, this.data.area_list[e.detail.value[2]].name],
        selectProvinceId: this.data.province_list[e.detail.value[0]].code,
        selectCityId: this.data.city_list[e.detail.value[1]].code,
        selectAreaId: this.data.area_list[e.detail.value[2]].code,
        'form.areaCode': this.data.area_list[e.detail.value[2]].code
      })
    }
  },

  //滑动地区组件
  bindRegionColumnChange:function(e){
    // console.log(e.detail.column,e.detail.value)
    let that = this
    let column = e.detail.column  //当前改变的列
    let data = {
      multiIndex:JSON.parse(JSON.stringify(that.data.multiIndex)),
      multiArray:JSON.parse(JSON.stringify(that.data.multiArray))
    }
    data.multiIndex[column] = e.detail.value  //第几列改变了就是对应multiIndex的第几个，更新他
    switch(column){
      case 0 :  //第一列改变，省级改变
        let currentProvinceId = that.data.province_list[e.detail.value].code
        if(currentProvinceId != that.data.currentProvinceId){ //判断当前id是不是更新了
          that.getCity(currentProvinceId)   //获取当前id下的市级数据
        }
        data.multiIndex[1] = 0    //将市默认选择第一个
        break
      case 1 :  //第二列改变，市级改变
        let currentCityId = that.data.city_list[e.detail.value].code
        if(currentCityId != that.data.currentCityId){
          that.getArea(currentCityId) //获取区域
        }
        data.multiIndex[2] = 0  //区域默认第一个
        break
    }
    that.setData(data)  //更新数据
  },
  /** 省市区 end **/

  /** 就职学校 start **/
  changeSchoolName(e) {
    this.setData({
      'form.schoolName': e.detail.value
    })
  },
  /** 就职学校 end **/

  /** 办学性质 start **/
  selectSchoolType() {
    this.setData({
      showSchoolType: true
    })
  },
  cancelSelectSchoolType() {
    this.setData({
      showSchoolType: false
    })
  },
  confirmSchoolType(e) {
    this.setData({
      schoolType: e.detail.name,
      'form.schoolType': e.detail.value
    })
  },
  /** 办学性质 end **/

  /** 选择科目 start **/
  selectSubject() {
    this.setData({showSubject: true})
  },

  cancelSelectSubject() {
    this.setData({showSubject: false})
  },

  checkSubject(e) {
    const item = e.currentTarget.dataset.item
    const index = e.currentTarget.dataset.index
    item.isCheck = !item.isCheck
    this.data.subjectList[index].isCheck = item.isCheck
    this.setData({
      subjectList: this.data.subjectList
    })
  },

  confirmSelectSubject() {
    this.data.selSubjects = []
    this.data.form.subjectId = []
    this.data.subjectList.forEach(subject => {
      if (subject.isCheck) {
        this.data.selSubjects.push(subject.name)
        this.data.form.subjectId.push(subject.code)
      }
    })
    this.setData({
      showSubject: false,
      selSubjects: this.data.selSubjects,
      'form.subjectId': this.data.form.subjectId
    })
  },
  /** 选择科目 end **/

  /** 选择学段 start **/
  selectPhase() {
    this.setData({showPhase: true})
  },

  cancelSelectPhase() {
    this.setData({showPhase: false})
  },

  confirmSelectPhase(e) {
    this.setData({
      showPhase: false,
      selPhases: e.detail.name,
      'form.phaseId': e.detail.code
    })
  },
  /** 选择学段 end **/


  getFindColumnList() {
    if (!this.data.goodAtList.length || !this.data.focusList.length || !this.data.trainList.length) {
      findColumnList({
        stageList: [this.data.form.phaseId],
        subjectList: this.data.form.subjectId
      }).then(res => {
        res.forEach(tag => {
          tag.isCheck = false;
          if (tag.sub && tag.sub.length) {
            tag.sub.forEach(s => {
              s.isCheck = false
            })
          }
        })
        this.setData({
          goodAtList: JSON.parse(JSON.stringify(res)),
          focusList: JSON.parse(JSON.stringify(res)),
          trainList: JSON.parse(JSON.stringify(res))
        })
      })
    }
  },

  /** 选择擅长内容 start **/
  async selectGoodAt() {
    if (!this.data.form.subjectId.length) {
      wx.showToast({
        title: '请先选择科目',
        icon: 'none',
        duration: 2000
      })
      return false;
    } else if (!this.data.form.phaseId.length) {
      wx.showToast({
        title: '请先选择学段',
        icon: 'none',
        duration: 2000
      })
      return false;
    } else {
      this.getFindColumnList()
      await this.setData({showGoodAt: true})
    }
  },

  cancelSelectGoodAt() {
    this.setData({showGoodAt: false})
  },

  checkGoodAt(e) {
    const item = e.currentTarget.dataset.item
    const index = e.currentTarget.dataset.index
    item.isCheck = !item.isCheck
    this.data.goodAtList[index].isCheck = item.isCheck
    this.setData({
      goodAtList: this.data.goodAtList
    })
  },

  confirmSelectGoodAt() {
    this.data.selGoodAt = []
    this.data.form.goodAtId = []
    this.data.goodAtList.forEach(goodAt => {
      if (goodAt.isCheck) {
        this.data.selGoodAt.push(goodAt.tagsName)
        this.data.form.goodAtId.push(goodAt.tagsId)
      }
    })
    this.setData({
      showGoodAt: false,
      selGoodAt: this.data.selGoodAt,
      'form.goodAtId': this.data.form.goodAtId
    })
    console.log(this.data.focusList)
  },
  /** 选择擅长内容 end **/

  /** 选择关注内容 start **/
  async selectFocus() {
    if (!this.data.form.subjectId.length) {
      wx.showToast({
        title: '请先选择科目',
        icon: 'none',
        duration: 2000
      })
      return false;
    } else if (!this.data.form.phaseId.length) {
      wx.showToast({
        title: '请先选择学段',
        icon: 'none',
        duration: 2000
      })
      return false;
    } else {
      await this.getFindColumnList()
      this.setData({showFocus: true})
    }
  },

  cancelSelectFocus() {
    this.setData({showFocus: false})
  },

  checkFocus(e) {
    const item = e.currentTarget.dataset.item
    const index = e.currentTarget.dataset.index
    item.isCheck = !item.isCheck
    this.data.focusList[index].isCheck = item.isCheck
    this.setData({
      focusList: this.data.focusList
    })
  },

  confirmSelectFocus() {
    this.data.selFocus = []
    this.data.form.focus = []
    this.data.focusList.forEach(focus => {
      if (focus.isCheck) {
        this.data.selFocus.push(focus.tagsName)
        this.data.form.focus.push(focus.tagsId)
      }
    })
    this.setData({
      showFocus: false,
      selFocus: this.data.selFocus,
      'form.focus': this.data.form.focus
    })
  },
  /** 选择关注内容 end **/

  /** 选择培训专长 start **/
  async selectTrain() {
    if (!this.data.form.subjectId.length) {
      wx.showToast({
        title: '请先选择科目',
        icon: 'none',
        duration: 2000
      })
      return false;
    } else if (!this.data.form.phaseId.length) {
      wx.showToast({
        title: '请先选择学段',
        icon: 'none',
        duration: 2000
      })
      return false;
    } else {
      await this.getFindColumnList()
      this.setData({showTrain: true})
    }
  },

  cancelSelectTrain() {
    this.setData({showTrain: false})
  },

  checkTrain(e) {
    const item = e.currentTarget.dataset.item
    const index = e.currentTarget.dataset.index
    item.isCheck = !item.isCheck
    this.data.trainList[index].isCheck = item.isCheck
    this.setData({
      trainList: this.data.trainList
    })
  },

  confirmSelectTrain() {
    this.data.selTrain = []
    this.data.form.trainSpecialityId = []
    this.data.trainList.forEach(train => {
      if (train.isCheck) {
        this.data.selTrain.push(train.tagsName)
        this.data.form.trainSpecialityId.push(train.tagsId)
      }
    })
    this.setData({
      showTrain: false,
      selTrain: this.data.selTrain,
      'form.trainSpecialityId': this.data.form.trainSpecialityId
    })
  },
  /** 选择培训专长 end **/

  next() {
    function setToast(tips) {
      wx.showToast({
        title: tips,
        icon: 'none',
        duration: 2000
      })
    }

    if (!this.data.form.subjectId.length) {
      setToast('请选择科目');
      return false;
    } else if (!this.data.form.areaCode) {
      setToast('请选择就职城市');
      return false;
    } else if (!this.data.form.schoolName) {
      setToast('请输入就职学校');
      return false;
    } else if (!this.data.form.schoolType) {
      setToast('请选择办学性质');
      return false;
    } else if (!this.data.form.phaseId) {
      setToast('请选择学段');
      return false;
    }  else if (!this.data.form.goodAtId.length) {
      setToast('请选择擅长内容');
      return false;
    } else if (!this.data.form.focus.length) {
      setToast('请选择关注内容');
      return false;
    } else if (!this.data.form.trainSpecialityId.length) {
      setToast('请选择培训专长');
      return false;
    }
    saveTeacher(this.data.form).then(res => {
      wx.navigateTo({
        url: '/pages/completeInfoLast/completeInfoLast?key=teacher'
      })
    })
  }
})
